//
//  YHMeSetViewController.m
//  YHApp
//
//  Created by -- on 2021/6/19.
//

#import "HASetVC.h"
#import "HAUserInfoVC.h"
#import "HAAddressListVC.h"
#import "HANavViewController.h"
#import "HALoginVC.h"
#import "AppDelegate.h"
#import "TZImagePickerController.h"
#import "SYUploadImageNetworking.h"
#import "HAAccountVC.h"
#import "HACostVC.h"
#import "HACancelAccountPopView.h"
#import "HAYHForgetPwdVC.h"
#import "HARealNameVC.h"

@interface HASetVC ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic ,strong) NSMutableArray *dataArray;

@end

@implementation HASetVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
    [self initData];

    [self.tableView reloadData];
    
    // Do any additional setup after loading the view.
}

- (void)initData {
    [self.dataArray addObject:@"头像"];
    
    [self.dataArray addObject:@"实名认证"];
//    [self.dataArray addObject:@"信息"];
    [self.dataArray addObject:@"地址"];
    [self.dataArray addObject:@"修改登录密码"];
    [self.dataArray addObject:@"版本号"];

    if (HAUserDefaults.isLock == 1) {
        [self.dataArray addObject:@"结算账户"];
    }
    [self.dataArray addObject:@"退出登录"];
}

- (void)initUI{
    self.baseTLabel.text = @"设置";

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(app_topH+44);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *title = self.dataArray[indexPath.row];
    if ([title isEqualToString:@"头像"]) {
        return 150;
    }else if ([title isEqualToString:@"退出登录"]) {
        return 54+54+60;
    }
    return 54;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *title = self.dataArray[indexPath.row];

    if ([title isEqualToString:@"头像"]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellID"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCellID"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setCellUserIcon:cell.contentView];
        return cell;
    }else if ([title isEqualToString:@"信息"]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellID"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCellID"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setCellTitle:cell.contentView title:@"个人信息" isLine:YES];
        return cell;
    }else if ([title isEqualToString:@"地址"]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellID"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCellID"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setCellTitle:cell.contentView title:@"收货地址" isLine:YES];
        return cell;
    }else if ([title isEqualToString:@"退出登录"]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellID"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCellID"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setCellOutLogin:cell.contentView];
        return cell;
    }else if ([title isEqualToString:@"结算账户"]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellID"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCellID"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setCellTitle:cell.contentView title:@"结算账户" isLine:YES];
        return cell;
    }else if ([title isEqualToString:@"结算成本"]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellID"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCellID"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setCellTitle:cell.contentView title:@"结算成本" isLine:YES];
        return cell;
    }else if ([title isEqualToString:@"修改登录密码"]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellID"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCellID"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setCellTitle:cell.contentView title:@"修改登录密码" isLine:YES];
        return cell;
    }else if ([title isEqualToString:@"实名认证"]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellID"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCellID"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setCellTitle:cell.contentView title:@"实名认证" isLine:YES];
        return cell;
    }else if ([title isEqualToString:@"版本号"]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellID"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCellID"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setCellTitle:cell.contentView title:@"版本号" isLine:YES];
        return cell;
    }




    return [UITableViewCell new];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *title = self.dataArray[indexPath.row];

    if ([title isEqualToString:@"信息"]) {
        HAUserInfoVC *vc = [[HAUserInfoVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([title isEqualToString:@"地址"]) {
        HAAddressListVC *vc = [[HAAddressListVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([title isEqualToString:@"结算账户"]) {
        HAAccountVC *vc  =[[HAAccountVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([title isEqualToString:@"结算成本"]) {
        HACostVC *vc = [[HACostVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([title isEqualToString:@"修改登录密码"]) {
        HAYHForgetPwdVC *vc = [[HAYHForgetPwdVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([title isEqualToString:@"实名认证"]) {
        HARealNameVC *vc = [[HARealNameVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)outButtonClick {
    [HAHelper outUserInfo];
    [AppDelegate single].window.rootViewController = [[HANavViewController alloc]initWithRootViewController:[HALoginVC new]];
}

-(void)dButtonClick {
    WS(weakSelf)
    HACancelAccountPopView *menu = [[HACancelAccountPopView alloc]init];
    [menu show];
    
    menu.HACancelAccountPopViewSureBlock = ^(NSString * _Nonnull pwd) {
        
        SYRequest *request = [[SYRequest alloc]init];
        request.requestMethod = SYRequestMethodGET;
        request.requestUrl = @"auth/cancel";
        request.parms = @{
            @"password":pwd,
        };
        [MBProgressHUD showLoading:weakSelf.view];
        
        [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request] responseBlock:^(SYDataModel *dataModel) {
            if (dataModel.request == request) {
                [MBProgressHUD hideHUDForView:weakSelf.view];
                if (dataModel.err) {
                    [MBProgressHUD showError:@"网络错误"];
                    return;
                }
                if (dataModel.code == 1) {
                    
                    [MBProgressHUD showSuccess:@"您的账号已注销"];

                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [AppDelegate single].window.rootViewController = [[HANavViewController alloc]initWithRootViewController:[HALoginVC new]];
                    });

                }else {
                    [MBProgressHUD showError:dataModel.msg];
                }
            }
        }];

    };
}

-(void)setCellUserIcon:(UIView *)contentView {
    for (UIView *view in contentView.subviews) {
        [view removeFromSuperview];
    }
    
    contentView.backgroundColor = [UIColor khaBGColor];
    
    UIImageView *iconImgView  = [UIImageView ha_createImageView];
    iconImgView.userInteractionEnabled = YES;
    [iconImgView sd_setImageWithURL:[NSURL URLWithString:HAUserDefaults.avatar]];
    iconImgView.backgroundColor = [UIColor whiteColor];
    iconImgView.layer.cornerRadius = 47;
    iconImgView.layer.masksToBounds = YES;
    iconImgView.contentMode =  UIViewContentModeScaleAspectFill;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(iconImgViewClick)];
    [iconImgView addGestureRecognizer:tap];
    [contentView addSubview:iconImgView];
    [iconImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.centerY.mas_equalTo(0);
        make.width.mas_offset(94);
        make.height.mas_offset(94);
    }];
    

}

-(void)setCellTitle:(UIView *)contentView title:(NSString *)title isLine:(BOOL)isLine {
    for (UIView *view in contentView.subviews) {
        [view removeFromSuperview];
    }
    
    UILabel *titLabel = [UILabel ha_NLabelWithFont:17 textColor:@"#000000" text:title alignment:0];
    [contentView addSubview:titLabel];
    [titLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.mas_equalTo(20);
    }];
    
    UIImageView *rightImageView = [UIImageView ha_createImageView];
    rightImageView.image = [UIImage imageNamed:@"ic_cell_more"];
    [contentView addSubview:rightImageView];
    [rightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(5);
        make.height.mas_offset(10);
        make.centerY.mas_equalTo(contentView);
        make.right.mas_equalTo(-20);
    }];
    
    if (isLine == YES) {
        UIView *lineView = [UIView ha_createView];
        lineView.backgroundColor = [UIColor kLineColor];
        [contentView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(contentView).offset(20);
            make.right.equalTo(contentView).offset(-20);
            make.height.equalTo(@0.6);
            make.bottom.equalTo(contentView);
        }];
    }
    
    if ([title isEqualToString:@"版本号"]) {
        rightImageView.hidden = YES;
        UILabel *conLabel = [UILabel ha_NLabelWithFont:17 textColor:@"#000000" text:@"v1.0.0" alignment:2];
        [contentView addSubview:conLabel];
        [conLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(0);
            make.right.mas_equalTo(-20);
        }];

    }

    
}


-(void)setCellOutLogin:(UIView *)contentView {
    for (UIView *view in contentView.subviews) {
        [view removeFromSuperview];
    }
    
    contentView.backgroundColor = [UIColor khaBGColor];
    
    UIButton *outButton = [[UIButton alloc]init];
    [outButton setTitle:@"退 出" forState:UIControlStateNormal];
    [outButton setTitleColor:[UIColor colorWithHexString:@"#676ADD"] forState:UIControlStateNormal];
    outButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    outButton.layer.cornerRadius = 4;
    outButton.layer.masksToBounds = YES;
    outButton.layer.borderColor = [UIColor colorWithHexString:@"#676ADD"].CGColor;
    outButton.layer.borderWidth = 0.6;
    [outButton addTarget:self action:@selector(outButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:outButton];
    [outButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(25);
        make.right.mas_equalTo(-25);
        make.centerY.mas_equalTo(-40);
        make.height.mas_offset(54);
    }];
    
    UIButton *dButton = [[UIButton alloc]init];
    [dButton setTitle:@"注销账户 >>>" forState:UIControlStateNormal];
    [dButton setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
    dButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [dButton addTarget:self action:@selector(dButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:dButton];
    [dButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(30);
        make.centerX.mas_equalTo(0);
        make.height.mas_offset(20);
        make.width.mas_offset(88);
    }];

}



- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        // 去掉滚动条
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        // 设置背景颜色
        _tableView.backgroundColor = [UIColor khaBGColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array ];
    }
    return _dataArray;
}

#pragma mark - 上传头像
-(void)iconImgViewClick {
    WS(weakSelf)
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil];
    imagePickerVc.allowCrop = YES;
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.needCircleCrop = NO;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.scaleAspectFillCrop = NO;
    CGFloat cropX = 0;
    CGFloat cropW = kUIScreen_w;
    CGFloat cropH = kUIScreen_w;
    CGFloat cropY = (kUIScreen_h-cropH)*0.5;
    imagePickerVc.cropRect = CGRectMake(cropX, cropY, cropW, cropH);
    imagePickerVc.didFinishPickingPhotosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        [weakSelf uploadImage:photos.firstObject];
    };
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

-(void)uploadImage:(UIImage *)image {
    WS(weakSelf)
    
    NSMutableDictionary *prams = [NSMutableDictionary dictionary];

    [MBProgressHUD showLoading:self.view];

    [[SYUploadImageNetworking shareSingle] initUploadImageUrl:@"common/avatar" param:prams image:image successBlock:^(SYDataModel * _Nonnull model) {

        [MBProgressHUD hideHUDForView:weakSelf.view];
        if ([[model.data allKeys]containsObject:@"fullurl"]) {
            NSString *fullurl = [NSString stringWithFormat:@"%@",[model.data valueForKey:@"fullurl"]];
            HAUserDefaults.avatar = fullurl;
            [weakSelf.tableView reloadData];
            [MBProgressHUD showSuccess:@"设置成功"];
        }

    } failureBlock:^(NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"上传失败"];
    } progressBlock:^(double progress) {

    }];

}


@end
